package com.entertainment.ticketing.controller;

import com.entertainment.ticketing.dto.LoginRequest;
import com.entertainment.ticketing.dto.LoginResponse;
import com.entertainment.ticketing.entity.UserInfo;
import com.entertainment.ticketing.repository.UserInfoRepository;
import com.entertainment.ticketing.security.JwtTokenProvider;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import java.util.Optional;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final UserInfoRepository userRepo;
    private final PasswordEncoder passwordEncoder;
    private final JwtTokenProvider tokenProvider;

    public AuthController(UserInfoRepository userRepo, PasswordEncoder passwordEncoder, JwtTokenProvider tokenProvider) {
        this.userRepo = userRepo;
        this.passwordEncoder = passwordEncoder;
        this.tokenProvider = tokenProvider;
    }

    @PostMapping("/login")
    public ResponseEntity<LoginResponse> login(@Valid @RequestBody LoginRequest req) {
        Optional<UserInfo> byUsername = userRepo.findByUsername(req.getUsernameOrEmail());
        Optional<UserInfo> byEmail = userRepo.findByEmail(req.getUsernameOrEmail());
        UserInfo user = byUsername.or(() -> byEmail).orElseThrow(() -> new ResponseStatusException(HttpStatus.UNAUTHORIZED, "用户不存在"));
        if (user.getStatus() == 0) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "用户已禁用");
        }
        String stored = user.getPassword();
        boolean matched = stored != null && passwordEncoder.matches(req.getPassword(), stored);
        if (!matched) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "用户名或密码错误");
        }
        String token = tokenProvider.generateToken(user);
        long expiresIn = tokenProvider.getExpirationMs();
        return ResponseEntity.ok(new LoginResponse(token, "Bearer", expiresIn));
    }
}